package com.itheima.web.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.domain.db.FreezeNews;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.FreezeService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.DateFormatUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import com.itheima.web.interceptor.AdminHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.*;

@Service
public class UserManager {

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private VideoService videoService;

    @Reference
    private MovementService movementService;

    @Reference
    private CommentService commentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private UserService userService;

    @Reference
    private FreezeService freezeService;

    public PageBeanVo findUserList(Integer pageNum, Integer pageSize) {
        //1. 调用service查询
        return userInfoService.findUserList(pageNum, pageSize);
    }

    public UserInfo findUserInfo(Long userId) {
        return userInfoService.findByUserId(userId);
    }

    //分页查询指定用户的小视频列表
    public PageBeanVo findUserVideoList(Long uid, Integer pageNum, Integer pageSize) {
        PageBeanVo pageBeanVo = videoService.findUserVideoList(uid, pageNum, pageSize);

        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        List<VideoVo> videoVoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                //3-1 创建videoVo
                VideoVo videoVo = new VideoVo();

                //3-2 设置用户信息
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());
                BeanUtil.copyProperties(userInfo, videoVo);

                //3-3 设置视频信息
                BeanUtil.copyProperties(video, videoVo);
                videoVo.setCover(video.getPicUrl());//设置封面图片
                videoVo.setSignature(video.getText());//设置文案
                videoVo.setHasLiked(1);//todo  实战修改

                //3-4  收集
                videoVoList.add(videoVo);
            }
        }

        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }

    //用户动态列表
    public PageBeanVo findUserMovementList(Long uid, Integer stateInt, Integer pageNum, Integer pageSize) {
        //1. 调用service查询
        PageBeanVo pageBeanVo = movementService.findUserMovementList(uid, stateInt, pageNum, pageSize);

        //2. 处理返回结果
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> movementVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(movementList)){
            for (Movement movement : movementList) {
                MovementVo movementVo = new MovementVo();
                movementVo.setUserInfo(userInfoService.findByUserId(movement.getUserId()));
                movementVo.setMovement(movement);
                movementVo.setCreateDate(DateUtil.offsetDay(new Date(movement.getCreated()),0).toDateStr());
                movementVoList.add(movementVo);
            }
        }
        pageBeanVo.setItems(movementVoList);
        return pageBeanVo;
    }

    //查询用户动态详情
    public MovementVo findMovementDetail(String movementId) {
        MovementVo movementVo = new MovementVo();
        Movement movement = movementService.findMovementById(movementId);
        movementVo.setUserInfo(userInfoService.findByUserId(movement.getUserId()));
        movementVo.setMovement(movement);
        movementVo.setCreateDate(DateUtil.offsetDay(new Date(movement.getCreated()),0).toDateStr());
        return movementVo;
    }

    //查询动态评论列表
    public PageBeanVo findMovementCommentList(String movementId, Integer pageNum, Integer pageSize) {
        //1. 调用service查询
        PageBeanVo pageBeanVo = commentService.findMovementCommentList(movementId, pageNum, pageSize);

        //2. 处理返回结果
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> commentVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                //1. 创建CommentVo
                CommentVo commentVo = new CommentVo();

                //2. 设置用户信息
                UserInfo userInfo = userInfoService.findByUserId(comment.getUserId());
                commentVo.setAvatar(userInfo.getAvatar());
                commentVo.setNickname(userInfo.getNickname());


                //3. 设置评论信息
                commentVo.setId(comment.getId().toHexString());
                commentVo.setContent(comment.getContent());
                commentVo.setCreateDate(DateFormatUtil.format(new Date(comment.getCreated())));

                //4. vo放入临时集合
                commentVoList.add(commentVo);
            }
        }

        pageBeanVo.setItems(commentVoList);
        return pageBeanVo;
    }


    //用户冻结
    public String userFreeze(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {

        //根据userId查询用户基本信息（包含用户id和用户手机号）
       User user = userService.findUserByUserId(userId);

        //创建对象
        FreezeNews freezeNews = new FreezeNews();
        freezeNews.setUserId(userId.longValue());
        freezeNews.setFreezingTime(freezingTime);
        freezeNews.setFreezingRange(freezingRange);
        freezeNews.setReasonsForFreezing(reasonsForFreezing);
        freezeNews.setFrozenRemarks(frozenRemarks);

        //调用service将数据放在数据库中
       freezeService.saveFreezeNews(freezeNews);
       //将用户状态放入userInfo表中（1 为正常；2 为用户冻结）
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("2");
        userInfoService.update(userInfo);

        //4. 创建token
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", userId);
        tokenMap.put("phone", user.getPhone());
        String token = JwtUtil.createToken(tokenMap);

        //判断冻结时间（1为冻结3天，2为冻结7天，3为永久冻结）
        //冻结范围（1为冻结登录，2为冻结发言，3为冻结状态）
        if (freezingTime==1) {
            //冻结三天(将冻结时间放入redis中，设置冻结时间)
            stringRedisTemplate.opsForValue().set(ConstantUtil.Freeze_Time+userId,freezingTime.toString(), Duration.ofDays(3));
        }else if (freezingTime==2){
            //冻结七天(将键值对保存在redis中)
            stringRedisTemplate.opsForValue().set(ConstantUtil.Freeze_Time+userId,freezingTime.toString(),Duration.ofDays(7));
        }else if (freezingTime==3){
            //永久冻结
            stringRedisTemplate.opsForValue().set(ConstantUtil.Freeze_Time + userId, freezingTime.toString());
        }
        if (freezingRange==1) {
            //冻结范围是登录
            stringRedisTemplate.opsForValue().set(ConstantUtil.Freeze_Range+userId,freezingRange.toString());
            stringRedisTemplate.delete(ConstantUtil.USER_TOKEN+token);
        }else if (freezingRange==2){
            //冻结范围是发言
            stringRedisTemplate.opsForValue().set(ConstantUtil.Freeze_Range+userId,freezingRange.toString());
        }else if (freezingRange==3){
            //冻结范围是：永久发布状态状态
            stringRedisTemplate.opsForValue().set(ConstantUtil.Freeze_Range+userId,freezingRange.toString());
        }


        return "冻结用户！";
    }

    //解冻操作
    public String unfreezeUser(Integer userId, String frozenRemarks) {

        //创建实体对象
        FreezeNews freezeNews = new FreezeNews();
        freezeNews.setUserId(userId.longValue());
        freezeNews.setReasonsForThawing(frozenRemarks);

        //调用service，将用户冻结标识修改过来
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId.longValue());
        userInfo.setUserStatus("1");
        //调用service，更新标识码
        userInfoService.update(userInfo);

        //将数据更新在冻结表格中
        freezeService.updateUnFreezeNews(freezeNews);

        //删除redis中保存的冻结标识
        stringRedisTemplate.delete(ConstantUtil.Freeze_Time+userId);
        stringRedisTemplate.delete(ConstantUtil.Freeze_Range+userId);


        return "解冻用户！";
    }

    //审核通过
    public String pass(String [] item) {
        for (String movementId : item){
            Movement movement = movementService.findMovementById(movementId);
            movement.setState(1);
            movementService.updateMovementState(movement);
        }
        String message = "已通过！";
        return message;
    }

    //审核驳回
    public String reject(String [] item) {
        for (String movementId : item){
            Movement movement = movementService.findMovementById(movementId);
            movement.setState(2);
            movementService.updateMovementState(movement);
        }
        String message = "已驳回！";
        return message;
    }
}
